package com.gzbd.login.shiro;

import com.gzbd.login.jwt.JwtToken;
import com.gzbd.login.jwt.JwtTokenUtil;
import com.gzbd.login.jwt.JwtUtil;
import jdk.nashorn.internal.parser.TokenType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @author xlj
 * @version 1.0
 * @description: TODO
 * @date 2024/2/22 15:02
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    /**
     * redis过期时间设置
     */
    @Value("${custom.jwt.expire_time}")
    private long expireTime;

    /**
     * 设置对应的token类型
     * 必须重写此方法，不然Shiro会报错
     *
     * @param token 令牌
     * @return boolean
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权认证
     *
     * @return {@link AuthorizationInfo}
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("————权限认证————");
//        String username = JWTUtil.getUsername(principals.toString());
        String token = principals.toString();
        Date date = jwtTokenUtil.getCreatedDateFromToken("USER", token);
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getCredentials();
        if (token == null) {
            token = jwtToken.getUsername();
        }
        if (token == null) {
            throw new UnauthenticatedException("不接受该请求！");
        }
        String userId = jwtTokenUtil.getUsernameFromToken("USER", token);

        if (userId == null || !jwtTokenUtil.validateToken("USER", token, userId)) {
            throw new AuthenticationException("token认证失败！");
        }
        /*UserVO user = userService.getUserVO(userId);
        if (user == null) {
            throw new AuthenticationException("该用户不存在！");
        }*/
        return new SimpleAuthenticationInfo(token, token, "username");
    }

}
